package com.laxcen.basiclib.core.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.laxcen.basiclib.utils.JsonUtil;
import com.laxcen.basiclib.utils.LogUtil;

import java.util.HashMap;
import java.util.Map;

/**
 *  广播管理的封装
 */
public class BroadcastManager {

    private Context mContext;
    private static BroadcastManager instance;
    private Map<String, BroadcastReceiver> receiverMap;
    private BroadcastManager(Context context) {
        this.mContext = context.getApplicationContext();
        receiverMap = new HashMap<>();
    }

    /**
     *  获取单实例
     * @param context
     * @return
     */
    public static BroadcastManager getInstance(Context context) {
        if (instance == null) {
            synchronized (BroadcastManager.class) {
                if (instance == null) {
                    instance = new BroadcastManager(context);
                }
            }
        }
        return instance;
    }

    /**
     * 注册订阅
     * @param
     */
    public void register(String action, BroadcastReceiver receiver) {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(action);
            mContext.registerReceiver(receiver, filter);
            receiverMap.put(action, receiver);
        } catch (Exception e) {
            LogUtil.e("broadcast.addAction->error",e.getMessage());
        }
    }
    /**
     * 取消订阅
     * 在onDestory调这个方法
     * @param action
     */
    public void unregister(String action) {
        if (receiverMap != null) {
            BroadcastReceiver receiver = receiverMap.remove(action);
            if (receiver != null) {
                mContext.unregisterReceiver(receiver);
            }
        }
    }

    /**
     * 发送广播
     * @param map
     */
    public void sendBroadcast(String action,Map<String,Object> map){
        Intent intent = new Intent();
        for(String key:map.keySet()){
            Object val = map.get(key);
            if(val instanceof Integer){
                intent.putExtra(key,(int)val);
            } else if(val instanceof Float){
                intent.putExtra(key,(float) val);
            }else if(val instanceof Double){
                intent.putExtra(key,(double) val);
            }else if(val instanceof Boolean) {
                intent.putExtra(key, (boolean) val);
            }else if(val instanceof Map){
                intent.putExtra(key, JsonUtil.beanToJson(val));
            }else {
                intent.putExtra(key,String.valueOf(val));
            }
        }
        intent.setAction(action);
        mContext.sendBroadcast(intent);
    }
}
